package cn.ekuma.epos.android.payment;

import cn.ekuma.android.keyBoardinput.KeyBoradInputPanel;
import cn.ekuma.android.keyBoardinput.KeyBoradInputPanel.ValueChangeListener;
import cn.ekuma.epos.ui.android.R;

import com.android.calculator2.Logic;
import com.android.calculator2.Logic.OnReturnListener;
import com.openbravo.bean.Customer;
import com.openbravo.bean.PaymentInfo;
import com.openbravo.bean.PaymentInfoCash;
import com.openbravo.format.Formats;
import com.openbravo.pos.payment.PaymentNotifier;
import com.openbravo.pos.util.RoundUtils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

public class PaymentCashPos extends AbstractPayment implements ValueChangeListener, OnReturnListener {

	KeyBoradInputPanel inputPanel;
	TextView m_jChangeEuros, m_jMoneyEuros;
	
	public PaymentCashPos(Context context, PaymentNotifier m_notifier) {
		super(context, m_notifier);
		View mainView = LayoutInflater.from(context).inflate( 
                R.layout.payment_cash, this); 
		inputPanel=(KeyBoradInputPanel) findViewById(R.id.payment_cash_key_import);
		m_jMoneyEuros= (TextView) findViewById(R.id.payment_selector_tackeuros);
		m_jChangeEuros= (TextView)findViewById(R.id.payment_selector_changeeuros);
		
		inputPanel.setValueChangeListener(this); 
		inputPanel.setInputListener(this);
	}

	public void activate(Customer customerext, double dTotal,
			String transactionID) {
		this.m_dTotal=dTotal;
		inputPanel.initData();
		printState();
	}

	public PaymentInfo executePayment() {
		if (RoundUtils.substract(m_dPaid , m_dTotal) >= 0.0) {
            // pago completo
            return new PaymentInfoCash(m_dTotal, m_dPaid);
        } else {
            // pago parcial
            return new PaymentInfoCash(m_dPaid, m_dPaid);
        } 
	}

	public void onValueChanged(String newValue) {
		printState();	
	}

	
	private void printState() {
        Double value = inputPanel.getDoubleValue();
        if (value == null || value == 0.0) {
            m_dPaid = m_dTotal;
        } else {            
            m_dPaid = value;
        }   

        int iCompare = RoundUtils.compare(m_dPaid, m_dTotal);
        
        m_jMoneyEuros.setText(Formats.CURRENCY.formatValue(new Double(m_dPaid)));
        m_jChangeEuros.setText(iCompare > 0 
                ? Formats.CURRENCY.formatValue(new Double(RoundUtils.substract(m_dPaid , m_dTotal)))
                : null); 
        
        m_notifier.setStatus(m_dPaid > 0.0, iCompare >= 0);
    }

	public void onReturn(String value) {
		// TODO Auto-generated method stub
		
	}

	public void onCommand(int command, String value) {
		if(Logic.COMMAND_equ==command){
			m_notifier.onEQUCommand();
		}
		
	}

	
}
